package org.chen.ctrip.scheduler;

import lombok.extern.slf4j.Slf4j;
import org.chen.common.ctrip.entity.Product;
import org.chen.ctrip.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;


@Slf4j
@Component
public class ProductDetailsScheduler {
    @Autowired
    private ProductService productService;

    @Autowired
    private ThreadPoolExecutor detailFetchExecutor;

    // 每30分钟检查一次未获取详情的商品
    @Scheduled(cron = "0 0 0/6 * * *") // 每六时执行一次
    public void fetchProductDetails() {
        log.info("开始获取商品详情");

        List<Product> unfetchedProducts = productService.getUnfetchedDetailProducts();

        if (unfetchedProducts.isEmpty()) {
            log.info("没有需要获取详情的商品");
            return;
        }

        log.info("发现{}个需要获取详情的商品", unfetchedProducts.size());

        // 异步处理，避免阻塞定时任务
        for (Product product : unfetchedProducts) {
            CompletableFuture.runAsync(() -> {
                try {
                    productService.fetchProductDetail(product.getId());

                    // 控制请求频率
//                    Thread.sleep(3000);
                } catch (Exception e) {
                    log.error("获取商品{}详情失败: {}", product.getId(), e.getMessage(), e);
                }
            }, detailFetchExecutor);
        }

        log.info("商品详情获取任务已提交");
    }
}
